package com.xhj.springbootproject.config;

import com.xhj.springbootproject.dao.BasicUserDao;
import com.xhj.springbootproject.dao.object.BasicUserDO;
import com.xhj.springbootproject.util.HashKit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

/**
 * @author ：Xionghaijun
 * @date ：Created in 2019/9/25 9:33 AM
 * @description：校验登录密码
 */
@Component
public class SelfAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    SelfUserDetailsService userDetailsService;

    @Autowired
    private BasicUserDao basicUserDao;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String userName = (String) authentication.getPrincipal();
        String password = (String) authentication.getCredentials();

        BasicUserDO basicUserDO = basicUserDao.queryUserInfoByUserName(userName);
        if (basicUserDO == null) {
            throw new BadCredentialsException("用户名不存在，请重新登录！");
        }
        password = HashKit.md5(password + basicUserDO.getUuid());

        Md5PasswordEncoder md5PasswordEncoder = new Md5PasswordEncoder();
        String encodePwd = md5PasswordEncoder.encodePassword(password, userName);

        UserDetails userInfo = userDetailsService.loadUserByUsername(userName);

        if (!userInfo.getPassword().equals(encodePwd)) {
            throw new BadCredentialsException("用户名密码不正确，请重新登陆！");
        }

        return new UsernamePasswordAuthenticationToken(userName, password, userInfo.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
